package com.itheima.wechat;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.JedisUtl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    JedisUtl jedisUtl;

    @Reference
    MemberService memberService;

    //校验验证码
    @RequestMapping("/check")
    public Result check(@RequestBody Map map) {
        //从前台获取参数
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis中获取validateCode
        String login = jedisUtl.get(telephone + RedisConstant.SMS_CODE_KEY_LOGIN);
        //如果后台没有验证码 或者验证码输入错误
        if (login == null || !login.equals(validateCode)) {
            return Result.ERROR(MessageConstant.VALIDATECODE_ERROR);
        }
        //根据手机号码查询是否是我们的会员
        Member member = memberService.findByTelephone(telephone);
        if (member == null) {
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            Member member1 = memberService.add(member);
            member = member1;
        }
        //把用户的登录状态保存到redis 生成一个UUID 保存到Redis中  //保证token不重复
        String token = UUID.randomUUID().toString() + member.getId();
        //JSON.toJSONString(member) 把会员信息转为json字符串存到redis,也可以使用redis里面的hash数据格式 15天时长
        jedisUtl.setex(token, 60 * 60 * 24 * 15, JSON.toJSONString(member));
        //token返回页面保存，下次发请求需要带上，后端需要去redis校验
        return Result.OK("", token);
    }

    @RequestMapping("/getFamily")
    public Result getFamily(HttpServletRequest request) {
        String token = request.getHeader("token");
        String memberJson = jedisUtl.get(token);
        Member member = JSON.parseObject(memberJson, Member.class);
        Integer id = member.getId();
        //通过id去查家庭联系人 自关联表
        List<Member> members = memberService.getFamily(member.getId());

        //回显电话
        String telephone = member.getPhoneNumber();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("members",members);
        map.put("telephone",telephone);
        return Result.OK("", map);
    }
}
